﻿using MengCC.App.Models;
using MengCC.Core.Plugins;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MengCC.App.Controllers
{
    public class PluginsController:Controller
    {
        private PluginManager pluginManager;
        private readonly IConfiguration configuration;

        public PluginsController(PluginManager pluginManager, IConfiguration configuration)
        {
            this.pluginManager = pluginManager;
            this.configuration = configuration;
        }


        public async Task<IActionResult> GetRepPlugins()
        {
            var plugins = pluginManager.GetPluginsByType(Core.Plugins.Plugin.PluginEnum.Repository);
            return new JsonResult(new Output<List<Core.Plugins.Plugin>>
            {
                code = 1,
                data = plugins
            });
        }

        public async Task<IActionResult> GetBuildPlugins()
        {
            var plugins = pluginManager.GetPluginsByType(Core.Plugins.Plugin.PluginEnum.Build);
            return new JsonResult(new Output<List<Core.Plugins.Plugin>>
            {
                code = 1,
                data = plugins
            });
        }
        public async Task<IActionResult> GetBuildedPlugins()
        {
            var plugins = pluginManager.GetPluginsByType(Core.Plugins.Plugin.PluginEnum.Builded);
            return new JsonResult(new Output<List<Core.Plugins.Plugin>>
            {
                code = 1,
                data = plugins
            });
        }

        public async Task<IActionResult>Index()
        {
            ViewBag.CurrentPlugins = pluginManager.GetAllPlugins();
            return View();
        }
        public async Task<IActionResult> Repository()
        {
            var plugins = pluginManager.LoadPluginDownloadList(configuration.GetSection("PluginReposityrUrl").Value);
            ViewBag.AvailablePlugins = plugins.GroupBy(p=>p.Name);
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> DeletePlugin(string pluginname, string platform)
        {
            pluginManager.RemovePlugin(pluginname,platform);
            return new JsonResult(new Output
            {
                code = 1
            });
        }

        [HttpPost]
        public async Task<IActionResult> DownloadPlugin(PluginDownloadConfig pluginDownloadConfig)
        {
            pluginManager.DownloadPlugin(pluginDownloadConfig);
            return new JsonResult(new Output
            {
                code = 1
            });
        }

        [HttpGet]
        public async Task<IActionResult> GetDownloadState(string pluginname,string platform)
        {
            return new JsonResult(new Output
            {
                code = pluginManager.GetPluginDownloadState(pluginname,platform)?1:0
            });
        }
    }
}
